package org.example.rsy.service.impl;

import com.alibaba.fastjson.JSON;
import org.apache.tika.metadata.serialization.JsonMetadataList;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.parser.RecursiveParserWrapper;
import org.apache.tika.sax.BasicContentHandlerFactory;
import org.apache.tika.sax.RecursiveParserWrapperHandler;
import org.example.rsy.exception.TikaException;
import org.example.rsy.service.BaseTikaService;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.io.StringWriter;

@Service
public class JsonTikaService extends BaseTikaService {

    @Override
    public String parse(InputStream inputStream) throws TikaException {

        RecursiveParserWrapperHandler recursiveParserWrapperHandler =
                new RecursiveParserWrapperHandler(new BasicContentHandlerFactory(
                        BasicContentHandlerFactory.HANDLER_TYPE.BODY, -1), -1);
        RecursiveParserWrapper wrapper = new RecursiveParserWrapper(initParse());
        try {
            wrapper.parse(inputStream, recursiveParserWrapperHandler, initMetadata(), new ParseContext());
            StringWriter writer = new StringWriter();
            JsonMetadataList.setPrettyPrinting(true);
            JsonMetadataList.toJson(recursiveParserWrapperHandler.getMetadataList(), writer);
            return JSON.toJSONString(writer.toString());
        } catch (Exception e) {
            throw new TikaException(e);
        }

    }

    @Override
    public String extractData() {

        return null;
    }

    @Override
    public int getCode() {
        return 6;
    }
}
